﻿using LKVMLMLib;
using PinService.Lib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Web;
using PinService.ViewModel;

namespace PinService.Lib
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MaThePaymentService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select MaThePaymentService.svc or MaThePaymentService.svc.cs at the Solution Explorer and start debugging.
    public class MaThePaymentService
    {
        public static string createSerial()
        {
            Random _random = new Random(Environment.TickCount);
            string alphabets = "ABCDEFGHIJKLMNPQRTUVXYZ";//"O-W-S"
            //string small_alphabets = "abcdefghijklmnpqrtuvxyz";
            string numbers = "1234567890";
            string characters = alphabets + numbers;
            int length = 9;
            string otp = string.Empty;
            for (int i = 0; i < length; i++)
            {
                string character = string.Empty;
                do
                {
                    int index = _random.Next(0, characters.Length);
                    character = characters.ToCharArray()[index].ToString();
                } while (otp.IndexOf(character) != -1);
                otp += character;
            }
            int _ascii1 = 0;
            int _ascii2 = 0;
            int _ascii3 = 0;
            otp.Substring(0, 3).ToList().ForEach(s =>
            {
                _ascii1 = _ascii1 + (int)s;
            });
            otp.Substring(3, 3).ToList().ForEach(s =>
            {
                _ascii2 = _ascii2 + (int)s;
            });
            otp.Substring(6, 3).ToList().ForEach(s =>
            {
                _ascii3 = _ascii3 + (int)s;
            });
            int _lastChar = Convert.ToInt32(_ascii1.ToString().Substring(_ascii1.ToString().Length - 1, 1))
                            + Convert.ToInt32(_ascii2.ToString().Substring(_ascii2.ToString().Length - 1, 1))
                            + Convert.ToInt32(_ascii3.ToString().Substring(_ascii3.ToString().Length - 1, 1));
            otp = otp + _lastChar.ToString().PadLeft(2, '0');
            var _dnow = DateTime.Now;
            return otp;
        }
        public string generateMaThe()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                int range = db.MaThes.Count();
                string mathe = string.Empty;
                if (range == 0)
                {
                    mathe = createSerial();
                    return mathe;
                }
                else
                {
                    for (int i = 0; i < Int32.MaxValue; i++)
                    {
                        mathe = createSerial();
                        var kq = db.MaThes.Where(w => w.Series == mathe).FirstOrDefault();
                        if (kq == null)
                            break;
                    }
                    return mathe;
                }
            }
        }
        public int insertMaThe(MaThe mt)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                db.MaThes.Add(mt);
                db.SaveChanges();
                var idLast = db.MaThes.OrderByDescending(x => x.ID).FirstOrDefault();
                if (idLast != null)
                    return idLast.ID;
                else
                    return 0;
            }
        }
        public MaThe findMaTheBySeri(string _seri)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var _mathe = db.MaThes.Where(s => s.Series == _seri).FirstOrDefault();
                return _mathe;
            }
        }
        public Dictionary<string, string> ActiveSeries(double package, string _code)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                Dictionary<string, string> _result = new Dictionary<string, string>();
                db.Configuration.ProxyCreationEnabled = false;
                var _val = db.MaThes.Where(s => s.Amount == package && s.Series == _code).FirstOrDefault();
                if (_val == null)
                {
                    _result.Add("ERROR", "Mã thẻ không đúng");
                    return _result;
                }
                else if (_val != null && _val.Used == true)
                {
                    _result.Add("ERROR", "Mã thẻ đã được sử dụng");
                    return _result;
                }
                else
                {
                    _val.Used = true;
                    db.SaveChanges();
                    _result.Add("SUCCESS", "Kích hoạt thành công");
                    return _result;
                }

            }
        }
        public MaThe[] getListMaThe(string keyword = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                if (!String.IsNullOrEmpty(keyword))
                {
                    return db.MaThes.Where(s => s.Series.Contains(keyword)).ToArray();
                }
                else
                {
                    return db.MaThes.ToArray();
                }

            }
        }
        public bool deleteMaThe(int Id)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var _maThe = db.MaThes.Where(s => s.ID == Id).FirstOrDefault();
                if (_maThe == null)
                    return false;
                else
                {
                    db.MaThes.Remove(_maThe);
                    db.SaveChanges();
                    return true;
                }
            }
        }
        public List<PinView> ListCardByUser(int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                //type= 0: PH | type = 1: mở khóa tài khoản | type = 2: chuyển pin
                db.Configuration.ProxyCreationEnabled = false;
                var ListPin = db.MaThes.Where(w => w.UserId == UserId)
                    .OrderByDescending(o => o.CreateDate)
                    .AsEnumerable()
                    .Select(
                    s => new PinView()
                    {
                        DataCreate = s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                        Id = s.ID,
                        PinCode = s.Series,
                        Used = s.Used != null ? s.Used.Value : false,
                        UsedType = s.UsedType
                    })
                    .ToList();
                return ListPin;
            }
        }
        public PinRate GetPinRate()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var ListPin = db.PinRates.Where(w => w.Id == 1).FirstOrDefault();
                return ListPin;
            }
        }
        public int AddPin(MaThe mathe)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                db.MaThes.Add(mathe);
                return db.SaveChanges();
            }
        }
        public bool checkPin(int userid)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    var hispin = db.MaThes.Where(w => w.Used != true && w.UserId == userid);
                    if (hispin.Count() > 0)
                    {

                        return true;
                    }
                    else return false;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }
        public bool checkMultiPin(int userid, int qty)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    var hispin = db.MaThes.Where(w => w.Used != true && w.UserId == userid);
                    if (hispin.Count() >= qty)
                    {

                        return true;
                    }
                    else return false;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }
        public bool usePin(int userid)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    var hispin = db.MaThes.Where(w => w.Used != true && w.UserId == userid);
                    if (hispin.Count() > 0)
                    {
                        var use = hispin.FirstOrDefault();
                        use.Used = true;
                        db.SaveChanges();
                        return true;
                    }
                    else return false;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }
        public bool usePinById(int Id = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try
                {
                    db.Configuration.ProxyCreationEnabled = false;
                    if (Id > 0)
                    {
                        var pin = db.MaThes.Where(w => w.ID == Id).FirstOrDefault();
                        if (pin != null)
                        {
                            pin.Used = true;
                            db.SaveChanges();
                            return true;
                        }
                        else
                            return false;
                    }
                    else
                        return false;
                }
                catch (Exception e)
                {
                    return false;
                }
            }
        }
        public MaThe[] getListMaThe()
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.MaThes.Where(mt => mt.EnterRoom != true).ToArray();

            }
        }
        public bool updateEnterRoom(MaThe maThe)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var mt = db.MaThes.Where(m => m.UserId == maThe.UserId).FirstOrDefault();
                mt.Amount = maThe.Amount;
                mt.CreateDate = maThe.CreateDate;
                mt.Series = maThe.Series;
                mt.EnterRoom = maThe.EnterRoom;
                mt.Used = maThe.Used;
                mt.UserId = maThe.UserId;
                db.SaveChanges();
                return true;

            }
        }
        public MaThe getMaTheByUserId(int UserId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.MaThes.Where(m => m.UserId == UserId && m.EnterRoom == false).FirstOrDefault();
            }
        }
        public string transferPin(int Id = 0, int userTo = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try
                {
                    if (Id == 0 || userTo == 0)
                        return "Invalid data input";
                    var pin = db.MaThes.Where(w => w.ID == Id && w.Used != true).FirstOrDefault();
                    if (pin == null)
                        return "Pin not found";
                    pin.UserId = userTo;
                    db.SaveChanges();
                    return "*";
                }
                catch (Exception ex)
                {
                    return "Error line";
                }
            }
        }
        public int countPinOfUser(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                return db.MaThes.Where(w => w.Used != true && w.UserId == userId).ToList().Count();
            }
        }
        public bool checkPasswordLevel2(int userId = 0, string password2 = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                if (user == null || String.IsNullOrWhiteSpace(password2))
                    return false;
                if (password2.Equals(user.SecondPassword))
                    return true;
                else
                    return false;
            }
        }
        //Chuyển pin có số lượng
        public bool transferPinOfQuantity(int userSend = 0, int userRecieve = 0, int quantity = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                if (userSend == 0 || userRecieve == 0 || quantity == 0)
                    return false;
                var ls = db.MaThes.Where(w => w.Used != true && w.UserId == userSend).OrderByDescending(o => o.CreateDate).ToList();
                if (ls.Count == 0)
                    return false;
                ls = ls.Take(quantity).ToList();
                string charPin = "";
                foreach (var item in ls)
                {
                    item.UserId = userRecieve;
                    charPin += "," + item.Series;
                }
                charPin = charPin.Remove(0, 1);
                var _code = RandomString(10);
                var pinHisSend = new PinHistory();
                pinHisSend.Amount = quantity;
                pinHisSend.Collection = charPin;
                pinHisSend.CreateDate = DateTime.Now;
                pinHisSend.UserId = userSend;
                pinHisSend.InOut = false;//Out
                pinHisSend.Description = "Send pin";
                pinHisSend.Code = _code;
                pinHisSend.UserConfirm = userRecieve;
                pinHisSend.UserNameConfirm = db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault().UserName;
                db.PinHistories.Add(pinHisSend);

                var pinHisRecieve = new PinHistory();
                pinHisRecieve.Amount = quantity;
                pinHisRecieve.Collection = charPin;
                pinHisRecieve.CreateDate = DateTime.Now;
                pinHisRecieve.UserId = userRecieve;
                pinHisRecieve.InOut = true;//In
                pinHisRecieve.Description = "Recieve Pin";
                pinHisRecieve.Code = _code;
                pinHisRecieve.UserConfirm = userSend;
                pinHisRecieve.UserNameConfirm = db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault().UserName;
                db.PinHistories.Add(pinHisRecieve);
                db.SaveChanges();
                return true;
            }
        }
        //tìm user
        public UserProfile findUserbyUserId(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                return db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
            }
        }
        //lấy pin có ngày tạo sớm nhất
        public string getPinEarlyDate(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                var pin = db.MaThes.Where(w => w.UserId == userId && w.Used != true).OrderBy(o => o.CreateDate).FirstOrDefault();
                if (pin != null)
                    return pin.Series;
                else
                    return null;
            }
        }
        //lấy time từ pin sử dụng gần nhất tới nay
        public TimeSpan getTimePinUsedNearly(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                var dd = new TimeSpan(0, 0, 0, 0, 0);
                var pin = db.MaThes.Where(w => w.UserId == userId && w.Used == true && w.UsedDate != null).OrderBy(o => o.UsedDate).ToList().LastOrDefault();
                if (pin != null)
                {
                    var check = DateTime.Now.Date.AddHours(8);
                     dd = DateTime.Now.Date.AddHours(8).Subtract(pin.UsedDate.Value);
                }
                return dd;
            }
        }
        //check kích pin là lần đầu
        public bool checkUsedIsFirst(int userId)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                if (user == null)
                    return false;
                if (user.IsFirst == true && user.Status != true)
                    return true;
                else
                    return false;
            }
        }
        //Hàm sử dụng pin
        public bool activePin(string pin = "", int type = 0)
        {
            //type= 0: PH | type = 1: mở khóa tài khoản | type = 2: chuyển pin
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                var pn = db.MaThes.Where(w => w.Series.Equals(pin)).FirstOrDefault();
                if (pn == null)
                    return false;
                if (pn.Used == true)
                    return false;
                pn.Used = true;
                pn.UsedDate = DateTime.Now;
                if (type == 1)
                    pn.UsedType = "Unlock";
                if (type == 0)
                    pn.UsedType = "Create PH";
                if (type == 2)
                    pn.UsedType = "Transfer";
                var pinHis = new PinHistory();
                pinHis.Amount = 1;
                pinHis.Code = pn.Series;
                pinHis.CreateDate = DateTime.Now;
                pinHis.Description = type == 0 ? "Active pin for PH" : type == 1 ? "Unlock account" : "Transfer pin";
                pinHis.Collection = pn.Series;
                pinHis.Type = 1;
                pinHis.UserId = pn.UserId;
                db.PinHistories.Add(pinHis);
                db.SaveChanges();
                return true;
            }
        }
        //Hàm update User khi sử dụng pin lần đầu
        public bool editUserToNotFirst(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try {
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    user.IsFirst = false;
                    db.SaveChanges();
                    return true;
                } catch (Exception ex)
                {
                    return false;
                }
            }
        }
        //Hàm khóa User
        public bool lockUser(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try
                {
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    user.IsFirst = false;
                    user.Status = false;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
        //Hàm active User
        public bool activerUser(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try
                {
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    user.Status = true;
                    db.SaveChanges();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
        // thêm user vào PH khi push pin thành công
        public string createPH(int userId = 0,string pin = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try
                {
                    var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                    if (user == null)
                        return "Please login again";
                    if (String.IsNullOrEmpty(pin))
                        return "Pin does not exists";
                    // kiểm tra có PH đang chạy hay không
                    var runPH = db.PHs.Where(w => w.UserId != null && w.UserId == userId && (w.Status == 1 || w.Status == 0)).ToList();
                    if (runPH.Count > 0)
                        return "Please complete PH before create new PH";
                    // kiểm tra có đang GH hay không
                    var runGH = db.GHs.Where(w => w.UserId != null && w.UserId == userId && (w.Status == 1 || w.Status == 0) && w.Type != 1).ToList();
                    if(runGH.Count > 0)
                        return "Please complete GH before create new PH";
                    var pg = db.Packages.OrderBy(o => o.ID).FirstOrDefault();
                    if (pg == null)
                        return "Cannot find PH value";
                    var kq = activePin(pin, 0);
                    if (kq)
                    {
                        var ph = new PH();
                        ph.UserId = userId;
                        ph.Status = 0;//New
                        ph.Amount = pg.Price;
                        ph.CreateDate = DateTime.Now;
                        ph.Delivered = 0;
                        ph.Extant = pg.Price;
                        db.PHs.Add(ph);
                        db.SaveChanges();
                        return "***";
                    }
                    else
                        return "Fail";
                }
                catch (Exception ex)
                {
                    return "Fail";
                }
            }
        }
        // lấy lịch sử chuyển pin
        public List<PinHistoryView> getPinHistory(int userId = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var ls = new List<PinHistoryView>();
                try
                {
                   var getls = db.PinHistories.Where(w => w.UserId == userId).ToList();
                   if(getls.Count > 0)
                    { 
                       ls= getls.AsEnumerable().Select(s => new PinHistoryView
                            {
                                Amount = s.Amount != null ? s.Amount.Value : 0,
                                CreateDate = s.CreateDate != null ? s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt") : "",
                                Description = s.Description,
                                Collection = s.Collection,
                                UsedId = s.UserId != null ? s.UserId.Value : 0,
                                UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() != null ? db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName : "",
                                IntOut = s.InOut == null ? false : s.InOut.Value,
                                SendOrRecieve = s.InOut == null ? "Send" : s.InOut.Value == false ? "Send" : "Recieve",
                                Code = s.Code,
                                UserConfirm = s.UserConfirm != null ? s.UserConfirm.Value : 0,
                                UserNameConfirm = s.UserNameConfirm,
                                Type = s.Type
                            }).ToList();

                    }
                    return ls;
                }
                catch(Exception enm) { return ls; }
            }
        }
        //hàm cộng 10% pin tức 15k vào ví cộng đồng
        public bool addMoneyForWalletPublic(int userId = 0, string pin = "")
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try { 
                var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                var wl = db.WalletPublics.FirstOrDefault();
                wl.Balance += 15000;
                var wh = new WalletPublic_History();
                wh.UserId = userId;
                wh.Value = 15000;
                wh.Reason = pin;
                wh.Description = "Add 15000 as " + user.UserName + " activation pin <" + pin + ">";
                wh.CreateDate = DateTime.Now;
                db.WalletPublic_History.Add(wh);
                db.SaveChanges();
                return true;
                }catch(Exception ex)
                {
                    return false;
                }
            }
        }
        // hàm kích hoạt pin có số lượng
        public bool activePinByQuantum(int userId = 0, int Quantum = 0, int type = 0)
        {
            //type= 0: PH | type = 1: mở khóa tài khoản | type = 2: chuyển pin
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                try { 
                //lấy pin tạo gần nhất
                var user = db.UserProfiles.Where(w => w.UserId == userId).FirstOrDefault();
                if (user == null)
                    return false;
                if (Quantum == 0)
                    return false;
                var ls = db.MaThes.Where(w => w.UserId == userId && w.Used != true).OrderBy(o => o.CreateDate).Take(Quantum).ToList();
                foreach(var item in ls)
                {
                        item.Used = true;
                        //item.CreateDate = DateTime.Now;
                        if (type == 1)
                            item.UsedType = "Unlock";
                        if (type == 0)
                            item.UsedType = "Create PH";
                        if (type == 2)
                            item.UsedType = "Transfer";
                        var _code = RandomString(10);
                        var pinHis = new PinHistory();
                        pinHis.CreateDate = DateTime.Now;
                        pinHis.UserId = item.UserId;
                        pinHis.Description = "Un-lock account<"+item.Series+">";
                        pinHis.Code = _code;
                        db.PinHistories.Add(pinHis);
                }
                db.SaveChanges();
                return true;
                }catch(Exception ex)
                {
                    return false;
                }
            }
        }
        // Hàm thêm lịch sự pin khi Admin chuyển pin
        public bool addPinHistory(int userSend = 0 , int userRecieve = 0, int quantity = 0)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                try
                { 
                    if (userSend == 0 || userRecieve == 0 || quantity == 0)
                        return false;
                    var ls = db.MaThes.Where(w => w.Used != true && w.UserId == userSend).OrderByDescending(o => o.CreateDate).ToList();
                    if (ls.Count == 0)
                        return false;
                    ls = ls.Take(quantity).ToList();
                    string charPin = "";
                    foreach (var item in ls)
                    {
                        item.UserId = userRecieve;
                        charPin += "," + item.Series;
                    }
                    charPin = charPin.Remove(0, 1);
                    var _code = RandomString(10);
                    var pinHisSend = new PinHistory();
                    pinHisSend.Amount = quantity;
                    pinHisSend.Collection = charPin;
                    pinHisSend.CreateDate = DateTime.Now;
                    pinHisSend.UserId = userSend;
                    pinHisSend.InOut = false;//Out
                    pinHisSend.Description = "Send pin";
                    pinHisSend.Code = _code;
                    pinHisSend.UserConfirm = userRecieve;
                    pinHisSend.UserNameConfirm = db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == userRecieve).FirstOrDefault().UserName;
                    db.PinHistories.Add(pinHisSend);

                    var pinHisRecieve = new PinHistory();
                    pinHisRecieve.Amount = quantity;
                    pinHisRecieve.Collection = charPin;
                    pinHisRecieve.CreateDate = DateTime.Now;
                    pinHisRecieve.UserId = userRecieve;
                    pinHisRecieve.InOut = true;//In
                    pinHisRecieve.Description = "Recieve Pin";
                    pinHisRecieve.Code = _code;
                    pinHisRecieve.UserConfirm = userSend;
                    pinHisRecieve.UserNameConfirm = db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault() == null ? "" : db.UserProfiles.Where(w => w.UserId == userSend).FirstOrDefault().UserName;
                    db.PinHistories.Add(pinHisRecieve);
                    db.SaveChanges();
                    return true;
                }catch(Exception ex)
                {
                    return false;
                }
            }
        }
        public static string RandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var random = new Random();
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }

        /// <summary>
        /// (ToanDV)lấy danh sách pin active từ ngày đến ngày where type ==1
        /// </summary>
        /// <returns></returns>
        public Tuple<int,PinHistoryView[]> getPinActiveOnDay(DateTime fromDate, DateTime toDate, int fromPage = 0, int toPage = 50)
        {
            string connection = DuAnDaCapEntities.getDomain();
            using (var db = MaThePaymentEntities.initMaThePaymentEntities(connection))
            {
                db.Configuration.ProxyCreationEnabled = false;
                var query = db.PinHistories.Where(w => w.Type != null && w.Type == 1 && w.CreateDate.Value >= fromDate && w.CreateDate.Value <= toDate).ToList();
                if(query.Count > 0)
                { 
                    var sql = query.AsEnumerable().Select(s => new PinHistoryView
                    {
                        Amount = s.Amount.Value,
                        CreateDate = s.CreateDate.Value.ToString("dd/MM/yyyy hh:mm:ss tt"),
                        Description = s.Description,
                        Collection = s.Collection,
                        UsedId = s.UserId != null ? s.UserId.Value : 0,
                        UserName = db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault() != null ? db.UserProfiles.Where(w => w.UserId == s.UserId).FirstOrDefault().UserName : "",
                        IntOut = s.InOut == null ? false : true,
                        SendOrRecieve = s.InOut == null ? "Send" : s.InOut.Value == false ? "Send" : "Recieve",
                        Code = s.Code,
                        UserConfirm = s.UserConfirm,
                        UserNameConfirm = s.UserNameConfirm
                    }).ToList();
                    int totalItems = sql.Count();
                    if (fromPage == 0 || fromPage == 1)
                    {
                        return new Tuple<int, PinHistoryView[]>(totalItems, sql.OrderByDescending(x => x.CreateDate).Skip(0).Take(toPage).ToArray());
                    }
                    else
                        return new Tuple<int, PinHistoryView[]>(totalItems, sql.OrderByDescending(x => x.CreateDate).Skip(fromPage).Take(toPage).ToArray());
                }

                return new Tuple<int, PinHistoryView[]>(0,new PinHistoryView[0]);
            }
        }
    }

}
